﻿using System;
using System.Web.Mvc;
using PagedList;
using SIG.WebMVC.Filters;
using SIG.Infrastructure.Configs;
using SIG.ViewModel;
using SIG.InputModel.Admin.Ads;
using AutoMapper;
using SIG.Infrastructure.Helper;
using SIG.DAL.Dapper.Repositories;
using SIG.ViewModel.Admin.Downloads;
using System.Web.Hosting;
using System.IO;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class DownloadController : BaseController
    {

        private readonly FileRepository _fileService;     
        private readonly IMapper _mapper;
        public DownloadController(IMapper mapper)
        {
            _fileService = new FileRepository();       
            _mapper = mapper;
        }


        public ActionResult Index(int? page, int? positionId, string keyword)
        {
            FileListVM fileListVM = GetElements(page, keyword);
            ViewBag.PageSizes = new SelectList(Site.PageSizes());            
            return View(fileListVM);


        }

        private FileListVM GetElements(int? page, string keyword)
        {
            var fileListVM = new FileListVM();       
            fileListVM.Keyword = keyword;
            fileListVM.PageIndex = (page ?? 1);
            fileListVM.PageSize = SettingsManager.Ads.PageSize;
            int totalCount;
            var filelist = _fileService.GetListPagedItems(fileListVM.PageIndex, fileListVM.PageSize, fileListVM.Keyword, out totalCount);
            
            //  var specialistVMList = _mapper.Map<List<File>, List<FileVM>>(filelist);
            fileListVM.TotalCount = totalCount;
            fileListVM.Files = new StaticPagedList<DAL.Dapper.Model.File>(filelist, fileListVM.PageIndex, fileListVM.PageSize, fileListVM.TotalCount); ;
            return fileListVM;
        }

        [HttpGet]
        public PartialViewResult Add()
        {
            FileIM vFile = new FileIM
            {
                Active = true,
                Importance = 0
            };
            
            return PartialView("_Add", vFile);
        }


        [HttpPost]
        public JsonResult Add(FileIM vm)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            string filePath = HostingEnvironment.MapPath(vm.FileURL);
            if (!System.IO.File.Exists(filePath))
            {
                AR.Setfailure("无效的文件");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

          //  string fileName = Path.GetFileName(filePath);
            FileInfo f = new FileInfo(filePath);

            var file = _mapper.Map<DAL.Dapper.Model.File>(vm);
            file.FileSize = f.Length;

            file.CreatedBy = Site.CurrentUserName;
            file.CreatedDate = DateTime.Now;
            _fileService.Create(file);

            int count;
            int pageSize = SettingsManager.Ads.PageSize;
            var list = _fileService.GetListPagedItems(1, pageSize, string.Empty, out count);
            //  List<FileVM> fileList = _mapper.Map<List<File>, List<FileVM>>(list);
            AR.Data = RenderPartialViewToString("_FileList", list);

            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        [HttpGet]
        public ActionResult Edit(int Id)
        {
            var vFile = _fileService.GetById(Id);
            if (vFile != null)
            {

                var vm = _mapper.Map<FileIM>(vFile);
                
                return PartialView("_Edit", vm);
            }
            AR.Setfailure("未找到编辑项");
            return Json(AR, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        public JsonResult Edit(FileIM vm)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            string filePath = HostingEnvironment.MapPath(vm.FileURL);
            if (!System.IO.File.Exists(filePath))
            {
                AR.Setfailure("无效的文件");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

           // string fileName = Path.GetFileName(filePath);
            FileInfo f = new FileInfo(filePath);

            var file = _fileService.GetById(vm.Id);
            file.Title = vm.Title;
            file.FileURL = vm.FileURL;
            file.FileSize = f.Length;       


            file.CreatedBy = Site.CurrentUserName;
            file.CreatedDate = DateTime.Now;
      
            file.Active = vm.Active;

            // var file = _mapper.Map<File>(vm);
            _fileService.Update(file);
     
            // var fileVM = _mapper.Map<FileVM>(_fileService.GetByIdWithPosition(file.Id));
            AR.Id = file.Id;
            AR.Data = RenderPartialViewToString("_FileItem", file);

            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            var vFile = _fileService.GetById(id);

            if (vFile != null)
            {
                //string imgurl = Server.MapPath(vFile.ImageUrl);
                //if (System.IO.File.Exists(imgurl))
                //{
                //    System.IO.File.Delete(imgurl);    //删除缩略图
                //}

                _fileService.Delete(vFile);
                //   _unit.SaveChanges();
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            AR.Setfailure("删除失败");
            return Json(AR, JsonRequestBehavior.DenyGet);
        }



        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {
            var vFile = _fileService.GetById(id);
            if (vFile == null)
            {
                AR.Setfailure("操作失败");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            try
            {
                vFile.Active = !vFile.Active;
                _fileService.Update(vFile);
             
                //  var vm = _mapper.Map<FileVM>(vFile);
                AR.Data = RenderPartialViewToString("_FileItem", vFile);

                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }

    }
}
